﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Windows.Forms;
using Z16.BLI;

namespace Z16.SITE
{
    public partial class RelatorioHorasUserPorCc : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Session["CodPerfil"] == null) || (Session["CodUsr"] == null))
            {
                Response.Write("<script>window.location=\'Login.aspx';</script>");
                return;
            }

            if (!IsPostBack)
            {
                carregarUsuario();
                Chart1.Visible = false;
            }
        }

        private void carregarUsuario()
        {
            Usuario Usuario = new Usuario();

            ddlUsuario.Items.Clear();
            ddlUsuario.AppendDataBoundItems = true;
            ddlUsuario.Items.Insert(0, "SELECIONE");

            ddlUsuario.DataSource = Usuario.ListarUsuariosAtivo();
            ddlUsuario.DataValueField = "cod_usuario";
            ddlUsuario.DataTextField = "nome_usuario";
            ddlUsuario.DataBind();
        }

        protected void btnGerar_Click(object sender, EventArgs e)
        {
            Usuario usuario = new Usuario();
            CentroDeCusto cc = new CentroDeCusto();
            int? CodUsr = null;
            if (ddlUsuario.SelectedIndex > 0)
                CodUsr = Convert.ToInt32(ddlUsuario.SelectedValue);

            var listaAllUsers = usuario.ListarUsuarioRet(CodUsr);
            var listaAllCC = cc.ListarCentroDeCusto(null,null);

            if (!ValidaCampos())
                return;

            var dtIniPro = String.Format("{0:ddMMyyyy}", DateTime.Parse(txtDataIni.Text));
            var dtFinPro = String.Format("{0:ddMMyyyy}", DateTime.Parse(txtDataFim.Text));

            pnlRelatorio.Controls.Add(new LiteralControl("<table bgcolor =\'#000000\' border=\'0\' cellppading =\'1\'  cellspacing=\'1\' style=\"width: 100%\">"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TR>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD> <BR /> </TD>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));

            var dtGrafico = new DataTable();
            dtGrafico.Columns.Add(new DataColumn("Nome_Usuario"));
            dtGrafico.Columns.Add(new DataColumn("TOTMIN"));

            Usuario TotalHorasUser = new Usuario();

            for (int i = 0; i < listaAllUsers.Rows.Count; i++)
            {
                var codUsr = Convert.ToInt32(listaAllUsers.Rows[i]["Cod_Usuario"]);
                var listaTotalHorasUser = TotalHorasUser.TotalHorasCentroDeCustoUsuario(codUsr, dtIniPro, dtFinPro);

                if (i > 0)
                    pnlRelatorio.Controls.Add(new LiteralControl("<table bgcolor =\'#000000\' border=\'0\' cellppading =\'1\'  cellspacing=\'1\' style=\"width: 100%\">"));


                pnlRelatorio.Controls.Add(new LiteralControl("<tr bgcolor=\"#473C8B\">"));
                pnlRelatorio.Controls.Add(new LiteralControl("<td colspan=\'2\'><font color=\'white\'>" +
                    listaAllUsers.Rows[i]["Nome_Usuario"] + "</font></td>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<td align=\"center\"><font color=\'white\'> TOTAL HORAS: " +
                    listaTotalHorasUser.Rows[0]["TOTAL_MIUTO_USUARIOS"]+ "</font></td>"));
                pnlRelatorio.Controls.Add(new LiteralControl("</tr>"));

                string corFundo = "";

                pnlRelatorio.Controls.Add(new LiteralControl("<TR bgcolor=\"#836FFF\">"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>CENTRO DE CUSTO</TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>HORAS"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>%</TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));

                var totalHorasUser = Convert.ToInt32(listaTotalHorasUser.Rows[0]["TOTAL_MIUTO_USUARIO"]);

                //Aqui
                DataRow row = dtGrafico.NewRow();
                row["Nome_Usuario"] = listaAllUsers.Rows[i]["Nome_Usuario"].ToString();
                row["TOTMIN"] = listaTotalHorasUser.Rows[0]["TOTAL_MIUTO_USUARIO"].ToString();

                dtGrafico.Rows.Add(row);

                for (int j = 0; j < listaAllCC.Rows.Count; j++)
                {
                    var codCC = Convert.ToInt32(listaAllCC.Rows[j]["Cod_Centro_De_Custo"]);

                    Usuario HorasUsercc = new Usuario();
                    var listaHorasUsercc = HorasUsercc.HorasUserCentroDeCustoUsuario(codUsr, codCC, totalHorasUser, dtIniPro, dtFinPro);

                    if (corFundo == "#D7E2E8")
                        corFundo = "#FFFFFF";
                    else
                        corFundo = "#D7E2E8";

                    pnlRelatorio.Controls.Add(new LiteralControl("<TR bgcolor=\'" + corFundo + "\'>"));
                    pnlRelatorio.Controls.Add(new LiteralControl("<TD>" + listaAllCC.Rows[j]["NOME_CENTRO_DE_CUSTO"].ToString() + "</TD>"));
                    pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\">" + listaHorasUsercc.Rows[0]["TOTAL_MIUTO_USUARIO"].ToString() + "</TD>"));
                    pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\">" + listaHorasUsercc.Rows[0]["PORCENTAGEM_CENTRO_CUSTO"].ToString() + "</TD>"));
                    pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));
                }
                pnlRelatorio.Controls.Add(new LiteralControl("<TR>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD> <BR /> </TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));
                pnlRelatorio.Controls.Add(new LiteralControl("</table>"));
            }

            //Gera Gráfico Horas por Centro de Custo
            GenerateChart(Chart1, dtGrafico);
            Chart1.Visible = true;

        }

        private Boolean ValidaCampos()
        {
            if (txtDataIni.Text == "" || txtDataFim.Text == "")
            {
                MessageBox.Show("Informe o período da pesquisa.", "Data Inválida.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            return true;
        }

        public void GenerateChart(Chart currentChart, DataTable dtGrafico)
        {
            ChartComponents Components = new ChartComponents();

            List<double> yValues = new List<double>();
            List<string> xValues = new List<string>();

            currentChart.Series.Add(Components.CreateSeriesColumnControl("Disabled"));//Disabled, Inside, Outside 

            for (int i = 0; i < dtGrafico.Rows.Count; i++)
            {
                decimal totHoras = 0;

                if (dtGrafico.Rows[i]["TOTMIN"].ToString() != "")
                {
                    totHoras = decimal.Parse(dtGrafico.Rows[i]["TOTMIN"].ToString()) / 60;
                    totHoras = decimal.Round(totHoras, 2);
                }

                yValues.Add(double.Parse(totHoras.ToString()));
                xValues.Add(dtGrafico.Rows[i]["Nome_Usuario"].ToString());
            }

            currentChart.ChartAreas.Add(Components.CreateChartArea(0));
            currentChart.Series["Default"].Points.DataBindXY(xValues, yValues);
            currentChart.Width = Components.CreateChartWidth(500);
            currentChart.Height = Components.CreateChartHeight(300);
            currentChart.Series[0].IsValueShownAsLabel = true;
            currentChart.Series[0]["PointWidth"] = "0.5";
            currentChart.Titles.Add("Horas por Usuário");

            currentChart.DataBind();
        }

        public Chart CreateChartControl()
        {
            Chart chart = new Chart();
            return chart;
        }

        public class ChartData
        {
            public string X { get; set; }

            public double Y { get; set; }

            public string Legend { get; set; }
        }
    }
}